<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抓取源盖世数据智能分析平台</title>
    <!-- 固定样式引入 - 不可修改路径 -->
    <!-- 引入React和ReactDOM -->
    <script src="/libs/react.development.js"></script>
    <script src="/libs/react-dom.development.js"></script>

    <!-- 引入Material-UI核心依赖 -->
    <script src="/libs/material-ui.development.js"></script>
    <script src="/libs/emotion-react.umd.min.js"></script>
    <script src="/libs/emotion-styled.umd.min.js"></script>

    <!-- 引入Babel用于解析JSX -->
    <script src="/libs/babel.min.js"></script>

    <!-- 引入Material图标（可选） -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="/pages/app.css">
</head>

<body>
    <div id="root"></div>

    <!-- 固定脚本引入 - 不可修改路径 -->
    <script type="text/babel" data-type="module">
        // 固定核心库引入
        import iToolX, { iUpload, iUtils, iEmit } from "http://a72dfc24ac69ccae7cf363c09e192c19.editor.aibot.gasgoo.com/editor-ui/client.js?a72dfc24ac69ccae7cf363c09e192c19";
        import clientState from "/pages/clientState.js";

        // 从MUI导入所需组件
        const { 
            Button, 
            Card, 
            CardContent, 
            CardHeader, 
            Typography, 
            TextField, 
            Switch, 
            FormControlLabel, 
            Chip, 
            Box, 
            Grid, 
            Divider, 
            IconButton, 
            Tooltip,
            Alert,
            Snackbar,
            CircularProgress,
            Paper
        } = MaterialUI;

        // 创建React组件
        function App() {
            // 获取URL参数中的抓取源ID
            const urlParams = new URLSearchParams(window.location.search);
            const sourceId = parseInt(urlParams.get('id')) || 0;
            
            // 状态管理
            const [sourceDetail, setSourceDetail] = React.useState(null);
            const [loading, setLoading] = React.useState(true);
            const [editing, setEditing] = React.useState(false);
            const [editForm, setEditForm] = React.useState({});
            const [snackbar, setSnackbar] = React.useState({ open: false, message: '', severity: 'success' });
            const [saving, setSaving] = React.useState(false);

            // 获取抓取源详情
            const fetchSourceDetail = async () => {
                if (!sourceId) {
                    setSnackbar({ open: true, message: '无效的抓取源ID', severity: 'error' });
                    setLoading(false);
                    return;
                }

                try {
                    setLoading(true);
                    const response = await iToolX.modules.sourceManager.getSourceDetail(sourceId);
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    // 如果注释信息为 "???" 或不存在，则尝试从 localStorage 中获取注释信息
                    let comment = '';
                    if (response.data.comment && response.data.comment !== '???') {
                        comment = response.data.comment;
                    } else {
                        // 尝试从 localStorage 中获取注释信息
                        const sourceComments = JSON.parse(localStorage.getItem('sourceComments') || '{}');
                        comment = sourceComments[sourceId] || '';
                    }
                    
                    setSourceDetail({
                        ...response.data,
                        comment: comment
                    });
                    setEditForm({
                        siteUrl: response.data.site_url,
                        siteTitle: response.data.site_title,
                        isEnable: response.data.is_enable,
                        comment: comment
                    });
                } catch (error) {
                    console.error('获取抓取源详情失败:', error);
                    setSnackbar({ open: true, message: `获取抓取源详情失败: ${error.message}`, severity: 'error' });
                } finally {
                    setLoading(false);
                }
            };

            // 保存编辑
            const handleSave = async () => {
                try {
                    setSaving(true);
                    const response = await iToolX.modules.sourceManager.updateSource(
                        sourceId,
                        editForm.siteUrl,
                        editForm.siteTitle,
                        editForm.isEnable
                    );
                    
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    // 将注释信息存储到 localStorage 中
                    const sourceComments = JSON.parse(localStorage.getItem('sourceComments') || '{}');
                    sourceComments[sourceId] = editForm.comment;
                    localStorage.setItem('sourceComments', JSON.stringify(sourceComments));
                    
                    // 更新本地状态
                    setSourceDetail({
                        ...sourceDetail,
                        site_url: editForm.siteUrl,
                        site_title: editForm.siteTitle,
                        is_enable: editForm.isEnable,
                        comment: editForm.comment
                    });
                    
                    setEditing(false);
                    setSnackbar({ open: true, message: '抓取源信息已更新', severity: 'success' });
                } catch (error) {
                    console.error('更新抓取源失败:', error);
                    setSnackbar({ open: true, message: `更新抓取源失败: ${error.message}`, severity: 'error' });
                } finally {
                    setSaving(false);
                }
            };

            // 切换状态
            const handleToggleStatus = async (enable) => {
                try {
                    const response = await iToolX.modules.sourceManager.toggleSourceStatus(sourceId, enable);
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    // 更新本地状态
                    setSourceDetail({
                        ...sourceDetail,
                        is_enable: enable
                    });
                    setEditForm({
                        ...editForm,
                        isEnable: enable
                    });
                    
                    setSnackbar({ 
                        open: true, 
                        message: `抓取源已${enable ? '启用' : '禁用'}`, 
                        severity: 'success' 
                    });
                } catch (error) {
                    console.error('切换状态失败:', error);
                    setSnackbar({ open: true, message: `切换状态失败: ${error.message}`, severity: 'error' });
                }
            };

            // 处理表单变更
            const handleFormChange = (field, value) => {
                setEditForm({
                    ...editForm,
                    [field]: value
                });
            };

            // 关闭提示
            const handleCloseSnackbar = () => {
                setSnackbar({ ...snackbar, open: false });
            };

            // 初始化加载数据
            React.useEffect(() => {
                fetchSourceDetail();
            }, [sourceId]);

            // 导航到抓取源列表
            const navigateToSources = () => {
                window.location.href = '/pages/business/sources.html';
            };

            // 渲染加载状态
            if (loading) {
                return (
                    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                        <CircularProgress />
                    </div>
                );
            }

            // 渲染错误状态
            if (!sourceDetail) {
                return (
                    <div style={{ padding: '20px' }}>
                        <Alert severity="error">无法加载抓取源详情</Alert>
                    </div>
                );
            }

            return (
                <div className="page-wrapper">
                    {/* 顶部导航 */}
                    <header className="header">
                        <div className="container nav-container">
                            <a href="/pages/home.html" className="logo">
                                <div className="logo-icon">C</div>
                                <span>抓取源盖世数据智能分析平台</span>
                            </a>
                            <nav>
                                <ul className="nav-menu">
                                    <li className="nav-item">
                                        <a href="/pages/home.html" className="nav-link">首页</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/sources.html" className="nav-link active">抓取源</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/contentManagement.html" className="nav-link">抓取内容</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/analysisList.html" className="nav-link">抓取内容分析</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/promptTemplateManagement.html" className="nav-link">提示词管理</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/contentPoolManagement.html" className="nav-link">内容池管理</a>
                                    </li>
                                </ul>
                            </nav>
                            <div className="nav-actions">
                                <div className="search-box">
                                    <span className="material-icons search-icon">search</span>
                                    <input type="text" className="search-input" placeholder="搜索..." />
                                </div>
                            </div>
                        </div>
                    </header>

                    {/* 主体内容 */}
                    <main className="main-content">
                        <div className="container">
                            {/* 面包屑导航 */}
                            <Box sx={{ mb: 3 }}>
                                <Typography variant="body2" color="textSecondary">
                                    <a href="/pages/home.html" style={{ color: '#666', textDecoration: 'none' }}>首页</a>
                                    {' / '}
                                    <a href="/pages/business/sources.html" style={{ color: '#666', textDecoration: 'none' }}>抓取源</a>
                                    {' / '}
                                    <span style={{ color: '#333' }}>抓取源详情</span>
                                </Typography>
                            </Box>

                            {/* 页面标题和操作按钮 */}
                            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                                <Typography variant="h5" component="h1" sx={{ fontWeight: 600 }}>
                                    抓取源详情
                                </Typography>
                                <Box>
                                    <Button 
                                        variant="outlined" 
                                        startIcon={<span className="material-icons">arrow_back</span>}
                                        onClick={navigateToSources}
                                        sx={{ mr: 2 }}
                                    >
                                        返回列表
                                    </Button>
                                    {editing ? (
                                        <>
                                            <Button 
                                                variant="outlined" 
                                                onClick={() => setEditing(false)}
                                                disabled={saving}
                                                sx={{ mr: 2 }}
                                            >
                                                取消
                                            </Button>
                                            <Button 
                                                variant="contained" 
                                                startIcon={saving ? <CircularProgress size={20} color="inherit" /> : <span className="material-icons">save</span>}
                                                onClick={handleSave}
                                                disabled={saving}
                                            >
                                                保存
                                            </Button>
                                        </>
                                    ) : (
                                        <Button 
                                            variant="contained" 
                                            startIcon={<span className="material-icons">edit</span>}
                                            onClick={() => setEditing(true)}
                                        >
                                            编辑
                                        </Button>
                                    )}
                                </Box>
                            </Box>

                            {/* 抓取源详情卡片 */}
                            <Grid container spacing={3}>
                                {/* 基本信息 */}
                                <Grid item xs={12} md={8}>
                                    <Card className="card">
                                        <CardHeader 
                                            title="基本信息" 
                                            action={
                                                <Chip 
                                                    label={sourceDetail.is_enable ? "已启用" : "已禁用"} 
                                                    color={sourceDetail.is_enable ? "success" : "default"}
                                                    size="small"
                                                />
                                            }
                                        />
                                        <Divider />
                                        <CardContent>
                                            {editing ? (
                                                <Grid container spacing={2}>
                                                    <Grid item xs={12}>
                                                        <TextField
                                                            label="站点URL"
                                                            value={editForm.siteUrl}
                                                            onChange={(e) => handleFormChange('siteUrl', e.target.value)}
                                                            fullWidth
                                                            required
                                                        />
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <TextField
                                                            label="站点标题"
                                                            value={editForm.siteTitle}
                                                            onChange={(e) => handleFormChange('siteTitle', e.target.value)}
                                                            fullWidth
                                                            required
                                                        />
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <FormControlLabel
                                                            control={
                                                                <Switch
                                                                    checked={editForm.isEnable}
                                                                    onChange={(e) => handleFormChange('isEnable', e.target.checked)}
                                                                    color="primary"
                                                                />
                                                            }
                                                            label="启用抓取"
                                                        />
                                                    </Grid>
                                                </Grid>
                                            ) : (
                                                <Grid container spacing={2}>
                                                    <Grid item xs={12} sm={3}>
                                                        <Typography variant="body2" color="textSecondary">站点URL</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={9}>
                                                        <Typography variant="body1">{sourceDetail.site_url}</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={3}>
                                                        <Typography variant="body2" color="textSecondary">站点标题</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={9}>
                                                        <Typography variant="body1">{sourceDetail.site_title}</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={3}>
                                                        <Typography variant="body2" color="textSecondary">状态</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={9}>
                                                        <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                                            <Chip 
                                                                label={sourceDetail.is_enable ? "已启用" : "已禁用"} 
                                                                color={sourceDetail.is_enable ? "success" : "default"}
                                                                size="small"
                                                                sx={{ mr: 2 }}
                                                            />
                                                            <Button
                                                                variant="outlined"
                                                                size="small"
                                                                onClick={() => handleToggleStatus(!sourceDetail.is_enable)}
                                                                startIcon={<span className="material-icons">
                                                                    {sourceDetail.is_enable ? 'pause' : 'play_arrow'}
                                                                </span>}
                                                            >
                                                                {sourceDetail.is_enable ? '禁用' : '启用'}
                                                            </Button>
                                                        </Box>
                                                    </Grid>
                                                    <Grid item xs={12} sm={3}>
                                                        <Typography variant="body2" color="textSecondary">创建时间</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={9}>
                                                        <Typography variant="body1">{sourceDetail.create_at}</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={3}>
                                                        <Typography variant="body2" color="textSecondary">修改时间</Typography>
                                                    </Grid>
                                                    <Grid item xs={12} sm={9}>
                                                        <Typography variant="body1">{sourceDetail.modify_at}</Typography>
                                                    </Grid>
                                                </Grid>
                                            )}
                                        </CardContent>
                                    </Card>
                                </Grid>

                                {/* 状态监控 */}
                                <Grid item xs={12} md={4}>
                                    <Card className="card">
                                        <CardHeader title="状态监控" />
                                        <Divider />
                                        <CardContent>
                                            <Box sx={{ textAlign: 'center', py: 2 }}>
                                                <Box sx={{ 
                                                    width: 80, 
                                                    height: 80, 
                                                    borderRadius: '50%', 
                                                    backgroundColor: sourceDetail.is_enable ? '#E6FFFB' : '#FFF2E8',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    margin: '0 auto 16px'
                                                }}>
                                                    <span className="material-icons" style={{ 
                                                        fontSize: 40, 
                                                        color: sourceDetail.is_enable ? '#00FF41' : '#FA8C16' 
                                                    }}>
                                                        {sourceDetail.is_enable ? 'check_circle' : 'error'}
                                                    </span>
                                                </Box>
                                                <Typography variant="h6" sx={{ mb: 1 }}>
                                                    {sourceDetail.is_enable ? '运行正常' : '已停止'}
                                                </Typography>
                                                <Typography variant="body2" color="textSecondary">
                                                    {sourceDetail.is_enable 
                                                        ? '抓取源正在正常运行中' 
                                                        : '抓取源已停止，不会执行抓取任务'}
                                                </Typography>
                                            </Box>
                                        </CardContent>
                                    </Card>
                                </Grid>

                                {/* 注释信息 */}
                                <Grid item xs={12}>
                                    <Card className="card">
                                        <CardHeader title="注释信息" />
                                        <Divider />
                                        <CardContent>
                                            {editing ? (
                                                <TextField
                                                    label="注释"
                                                    value={editForm.comment}
                                                    onChange={(e) => handleFormChange('comment', e.target.value)}
                                                    fullWidth
                                                    multiline
                                                    rows={4}
                                                    placeholder="添加关于此抓取源的注释信息，如数据特点、用途、注意事项等"
                                                />
                                            ) : (
                                                <Typography variant="body1" sx={{ whiteSpace: 'pre-wrap' }}>
                                                    {sourceDetail.comment || '暂无注释信息'}
                                                </Typography>
                                            )}
                                        </CardContent>
                                    </Card>
                                </Grid>
                            </Grid>
                        </div>
                    </main>

                    {/* 页脚 */}
                    <footer className="footer">
                        <div className="container footer-content">
                            <ul className="footer-links">
                                <li><a href="#">帮助中心</a></li>
                                <li><a href="#">隐私政策</a></li>
                                <li><a href="#">服务条款</a></li>
                                <li><a href="#">联系我们</a></li>
                            </ul>
                            <div className="footer-copyright">
                                ? 2023 盖世数据智能分析平台. All rights reserved.
                            </div>
                        </div>
                    </footer>

                    {/* 提示消息 */}
                    <Snackbar
                        open={snackbar.open}
                        autoHideDuration={6000}
                        onClose={handleCloseSnackbar}
                    >
                        <Alert onClose={handleCloseSnackbar} severity={snackbar.severity} sx={{ width: '100%' }}>
                            {snackbar.message}
                        </Alert>
                    </Snackbar>
                </div>
            );
        }

        // 渲染组件到页面
        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<App />);
    </script>
</body>

</html>